<?php

namespace Biz\service\trade;

use Biz\model\OperateLog as mOperateLog;
use Biz\model\trade\ShopAddress as mShopAddress;
use Biz\service\OperateLog as sOperateLog;
use Doraemon\tools\Log as tLog;
use Biz\tools\ShopArea as tArea;
/**
 * @deprecated
 */
class ShopAddress
{
    public static function mgtCreateOrEdit($addressId, $data)
    {
        try {
            $area = '';
            $province = tArea::locationId2Name($data['province']);
            $city = tArea::locationId2Name($data['city']);
            if ($city == '市辖区' || $city == '县') {
                $city = '';
            }
            if ($data['area']) {
                $area = tArea::locationId2Name($data['area']);
            }
            $data['address'] = $province . $city . $area . $data['info_address'];
            if ($addressId) {
                $scenes = 'update';
                $result = mShopAddress::action(function () use ($data, $addressId, &$row) {
                    if (!mShopAddress::checkUserAddressById($addressId, $data['shop_id'])) {
                        throw new \Exception("没有该用户地址", 0);
                    }
                    if (mShopAddress::hasMasterAddressByShopId($data['shop_id'])) {
                        if ($data['is_default']) {
                            mShopAddress::updateDefaultAddressByShopId($data['shop_id'], 0);
                        }
                    }
                    $row = mShopAddress::saveAddressById($addressId, $data);
                });
                if ($result !== false) {
                    sOperateLog::record(mOperateLog::TYPE_ORDER_MGT_CHANGE_ADDRESS_STATUS, $data['shop_id'], $addressId, mShopAddress::getById($addressId), $data);
                    return $row;
                }
                throw new \Exception('修改地址失败', 0);
            } else {
                $scenes = 'insert';
                $result = mShopAddress::action(function () use ($data, &$id) {

                    if (mShopAddress::getCount($data['shop_id']) == 10) {
                        throw new \Exception('最多只能添加10个地址');
                    }

                    if (mShopAddress::hasMasterAddressByShopId($data['shop_id'])) {
                        if ($data['is_default']) {
                            mShopAddress::updateDefaultAddressByShopId($data['shop_id'], 0);
                        }
                    } else {
                        $data['is_default'] = 1;
                    }
                    $id = mShopAddress::insertAddress($data);
                });
                if ($result !== false) {
                    sOperateLog::record(mOperateLog::TYPE_ORDER_MGT_CHANGE_ADDRESS_STATUS, $data['shop_id'], 0, [], array_merge($data, ['id' => $id]));
                    return $id;
                }
                throw new \Exception('添加地址失败', 0);
            }
        } catch (\Exception $e) {

            tLog::warning('更新地址异常', [
                'shop_id'           => $data['shop_id'],
                'type'              => $scenes,
                'change_address_to' => $data,
                'edittime'          => date('Y-m-d H:i:s', time()),
                'e_msg'             => $e->getMessage(),
                'e_file'            => $e->getFile(),
                'e_line'            => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtGetList($shopId)
    {
        $addressList = [];
        $list = mShopAddress::selectAddressFieldsByShopId($shopId, ['id', 'province', 'city', 'area', 'accept_name', 'mobile', 'address', 'info_address', 'remark', 'is_default']);
        array_walk($list, function ($v, $k) use (&$addressList) {
            $addressList[$k] = $v;
            $addressList[$k]['key'] = $k;
            if (empty($v['area'])) {
                $addressList[$k]['address_code'] = [$v['province'], $v['city']];
            } else {
                $addressList[$k]['address_code'] = [$v['province'], $v['city'], $v['area']];
            }
        });
        return $addressList;
    }

    public static function mgtDelAddressById($addressId, $shopId)
    {
        try {
            $addressInfo = mShopAddress::getById($addressId);

            if ($addressInfo['shop_id'] != $shopId) {
                throw new \Exception('商家没有改地址的权限');
            }

            $result = mShopAddress::deleteAddressById($addressId);

            $row = $result->rowCount();

            if ($row > 0) {
                sOperateLog::record(mOperateLog::TYPE_ORDER_MGT_CHANGE_ADDRESS_STATUS, $shopId, $addressId, $addressInfo, []);
            }

            return $row;

        } catch (\Exception $e) {

            tLog::warning('删除地址异常', [
                'shop_id'    => $shopId,
                'address_id' => $addressId,
                'type'       => 'delete',
                'edittime'   => date('Y-m-d H:i:s', time()),
                'e_msg'      => $e->getMessage(),
                'e_file'     => $e->getFile(),
                'e_line'     => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtSetDefaultAddress($addressId, $shopId)
    {
        try {
            $result = mShopAddress::action(function () use ($addressId, $shopId, &$addressInfo, &$row) {

                $addressInfo = mShopAddress::getById($addressId);

                if ($addressInfo['shop_id'] != $shopId) {
                    throw new \Exception('商家没有改地址的权限');
                }

                if (mShopAddress::hasMasterAddressByShopId($shopId)) {
                    mShopAddress::updateDefaultAddressByShopId($shopId, 0);
                }

                $row = mShopAddress::setDefaultAddressById($addressId)->rowCount();

            });

            if ($result !== false) {
                sOperateLog::record(mOperateLog::TYPE_ORDER_MGT_CHANGE_ADDRESS_STATUS, $shopId, $addressId, ['is_default' => $addressInfo['is_default']], ['is_default' => 1]);
            }

            return $row;

        } catch (\Exception $e) {

            tLog::warning('设置默认地址异常', [
                'shop_id'    => $shopId,
                'address_id' => $addressId,
                'is_default' => 1,
                'edittime'   => date('Y-m-d H:i:s', time()),
                'e_msg'      => $e->getMessage(),
                'e_file'     => $e->getFile(),
                'e_line'     => $e->getLine()
            ]);

            throw $e;
        }
    }

    public static function mgtGetDetail($addressId, $shopId)
    {
        $addressInfo = mShopAddress::getById($addressId);

        if ($addressInfo['shop_id'] != $shopId) {
            throw new \Exception('商家没有改地址的查看权限');
        }

        return $addressInfo;
    }

    public static function getDefaultAddressByShopId($shopId)
    {
        return mShopAddress::getDefaultAddress($shopId);
    }
}